<template>
    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500"
            :before-close="closeDialog"
    >
        <el-form :model="forms"
                 :rules="rules"
                 label-width="auto"
                 style="max-width: 600px"
                 ref="formsRef">
            <el-form-item label="名称" prop="name">
                <el-input v-model="forms.name"/>
            </el-form-item>
            <el-form-item label="标识" prop="code">
                <el-input v-model="forms.code"/>
            </el-form-item>
            <el-form-item label="主题" prop="theme">
                <el-input v-model="forms.theme"/>
            </el-form-item>
            <el-form-item label="LOGO" prop="logo">
                <UploadImage @uploadSuccess="uploadSuccessLogo"></UploadImage>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input type="textarea" v-model="forms.description"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="doSubmit(formsRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup type="ts">
import {defineEmits, reactive, ref} from "vue";
import {createApp} from "@/api/api.app";
import UploadImage from '@/views/comps/upload/index.vue'
import {company, workspace} from "@/utils/core/store";

const emit = defineEmits(["submit"]);


const formsRef = ref();
const dialog = reactive({
    visible: false,
    title: '创建应用'
})

const forms = reactive({
    name: '',
    code: '',
    logo: '',
    description: '',
    theme: '',
    env: workspace.value.env,
    companyId: company.value.id
});

const rules = reactive({
    name: [
        {required: true, message: '请输入应用名称', trigger: 'blur'},
        {max: 20, message: '应用名称不能超过20个字符', trigger: 'blur'}
    ],
    code: [
        {required: true, message: '请输入应用标识', trigger: 'blur'}
    ]
})

const openDialog = () => {
    dialog.visible = true;
}

const closeDialog = () => {
    dialog.visible = false;
}

const uploadSuccessLogo = (base64) => {
    forms.logo = base64;
}

const doSubmit = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            createApp(forms).then(() => {
                closeDialog();
                emit("submit");
            });
        }
    })
}

const exposed = {
    openDialog
};
defineExpose(exposed);
</script>
